<?php

namespace App\Services\SpiderContent;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Blogger;
use App\Models\Video;
use App\Jobs\RewardFirstParentJob;
use Illuminate\Support\Facades\Log;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Database\Eloquent\Collection;
use Sunra\PhpSimple\HtmlDomParser;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Nesk\Puphpeteer\Puppeteer;
use Illuminate\Http\Request;

use DOMDocument;


class SpiderVideoAndOther
{


    public function execute($video)
    {
    	


    	 $parameters = [
            'aid' => $video->bli_aid,
            'isGaiaAvoided' => false,
            'need_view'=>1,
            'web_location'=>1315873
        ];
        $query = $this->get_bili_query($parameters);

        $url = "https://api.bilibili.com/x/web-interface/wbi/view/detail?$query";
        $json = $this->get_Url($url);

        $jsonObj = json_decode($json,true);
        
        $updateData = [
        	'like'=>$jsonObj['data']['View']['stat']['like'],
        	'collect'=>$jsonObj['data']['View']['stat']['favorite'],
        	'title'=>$jsonObj['data']['View']['title'],
        ];


    	ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)');

    	$url =$video->url;

    	$bvidArr = explode("/",$url);
    	$bvid = end($bvidArr);

    	$apiUrl = "https://api.pearktrue.cn/api/bilibili/parse.php?bvid=".$bvid."&sessdata=02eca6d5%2C1759658193%2C4062e%2A41CjD7LUeo2T24vXtrx211w7wpEmuZlj7av1m3uuVHRKBl3zhQrzHFMdC461chG4v-0K0SVk1OeGVZYS1YX2o2TEEtU0lkVVhjNG1BdlVxWGRhUzN6aWlZODJxU08zNkdoNllvcXJUYk1PUFd1Ny0xcXNqRnFzUEJPMUZIM2o4MDMzblg5MG55Um53IIE";

		$videoRes = $this->curl($apiUrl);


		$videoRes =  json_decode($videoRes,true);

		if($videoRes['code'] ==200 && !empty($videoRes['data']['videos'])){

			$realVideoUrl = $videoRes['data']['videos'][0]['videourl'];

			$updateData['video_url'] = $realVideoUrl;

			$video->update($updateData);
		}

    	/*$puppeteer = new Puppeteer; // 新建 Puppeteer 实例

         $browser = $puppeteer->launch(['args'=>['--no-sandbox']]); // 启动无头浏览器
         $page = $browser->newPage(); // 打开新的标签页
       
         $page->tryCatch->goto($url,[
         	 'idle_timeout' => 1000000,
             'timeout' => 0,
             'read_timeout' => 30

         ]); // 访问页面
       	 
         $html = $page->content();



      	//抓取video Start
         dd($html);

      	$jsonMatch = "/__playinfo__=(.*?)<\/script>/";
      	//$jsonMatch = "/__playinfo__=(.*?)windows/";

      	preg_match($jsonMatch,$html,$match);

      	//$browser->close();

        $json = json_decode($match[1],true);

        $browser->close();

        if(!isset($json['data']['dash'])){

        	$videoUrl = $json['data']['durl'][0]['url'];

        	$postName = Str::random(40). '.mp4';
			$outputFile =storage_path('app/public')."/".$postName; // 输出视频文件

			$videoUrl = str_replace('&', '\&', $videoUrl);

        	$ffmpegCommand = "ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl."  -c copy $outputFile";
			$res = exec($ffmpegCommand);


        }else{
	        $videoUrl = $json['data']['dash']['video'][0]['baseUrl'];
	        

	        $videoUrl = $this->checkBadRequest($videoUrl,0,$json,1);

	        $videoUrl = str_replace('&', '\&', $videoUrl);

	        $audioUrl = "";
	        if(isset($json['data']['dash']['audio'])){

	        	$audioUrl = $json['data']['dash']['audio'][0]['baseUrl'];
	      	    $audioUrl = $this->checkBadRequest($audioUrl,0,$json,2);
	      	    $audioUrl = str_replace('&', '\&', $audioUrl);
	        }
	       
			

			$postName = Str::random(40). '.mp4';
			$outputFile =storage_path('app/public')."/".$postName; // 输出视频文件
			

			if($audioUrl){
				$ffmpegCommand = "ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl." -i ".$audioUrl." -c copy $outputFile";

			}else{

				$ffmpegCommand = "ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl."  -c copy $outputFile";
			}

			
			$res = exec($ffmpegCommand);

		}

		

		Storage::putFileAs('/videos', $outputFile, $postName);
		
		$realVideoUrl = "/videos/".$postName;*/
		
	
		
 
		
    }


    public function djNodes($nodes,$res)
    {
    	if($nodes->nextSibling && $nodes->nextSibling->nodeName!="h4"){

    		$res['content'] = $res['content'].$nodes->nextSibling->textContent;


    		if($nodes->nextSibling->childNodes){

    			foreach($nodes->nextSibling->childNodes as $nn){
    				if($nn->nodeName=="img"){
    					$res['image'] = $nn->getAttribute('src');
    				}
    			}
    		}
    		
    		if(isset($nodes->nextSibling->nextSibling)  && $nodes->nextSibling->nextSibling->nodeName != "h4"){

    			 $res = $this->djNodes($nodes->nextSibling,$res);
    		}
    	}

    	return  $res;
    	//dd($nodes->nextSibling->nextSibling);
    	

    }

    public function checkBadRequest($url,$key,$json,$source)
    {

    	 if(strstr($this->getUrl($url),'An error occurred')){
        	//return $json['data']['dash']['video'][1]['baseUrl'];

    	 	$url  = str_replace("https","http",$url);

    	 	if(!strstr($this->getUrl($url),'An error occurred')){

    	 		return $url;
    	 	}
    	 	
    	 	if($source==1){

    	 		$url = $json['data']['dash']['video'][$key+1]['baseUrl'];
    	 	}else{

    	 		$url = $json['data']['dash']['audio'][$key+1]['baseUrl'];
    	 	}
        	

        	

        	if($url){
				$otherUrl = $this->checkBadRequest($url,$key+1,$json,$source);

        		return $otherUrl;

        	}else{

        		return '';
        	}
        		

        }

        return $url;
        	
    }


    //---------------获取用户信息开始---------------
	// 对 imgKey 和 subKey 进行字符顺序打乱编码
	function getMixinKey($orig) {
	    $mixinKeyEncTab = array(46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
	        33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40,
	        61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11,
	        36, 20, 34, 44, 52); // 将 mixinKeyEncTab 补充完整，包括各个元素的值
	    $temp = '';
	    foreach ($mixinKeyEncTab as $n) {
	        $temp .= $orig[$n];
	    }
	    return substr($temp, 0, 32);
	}

	// 为请求参数进行 wbi 签名
	function encWbi($params, $img_key, $sub_key) {
	    $mixin_key = $this->getMixinKey($img_key . $sub_key);

	    $curr_time = time();
	    $chr_filter = '/[!\'\(\)*]/';
	    $query = [];
	    $params['wts'] = $curr_time; // 添加 wts 字段
	    // 按照 key 重排参数
	    ksort($params);
	    foreach ($params as $key => $value) {
	        $filtered_value = preg_replace($chr_filter, '', (string)$value);
	        $query[] = urlencode($key) . '=' . urlencode($filtered_value);
	    }
	    $query_string = implode('&', $query);
	    $wbi_sign = md5($query_string . $mixin_key);
	    return $query_string . '&w_rid=' . $wbi_sign;
	}

	// 获取最新的 img_key 和 sub_key
	function getWbiKeys() {
	    $url = 'https://api.bilibili.com/x/web-interface/nav';
	    $json = $this->get_Url($url);
	    $data = json_decode($json, true);
	    $img_url = $data['data']['wbi_img']['img_url'];
	    $sub_url = $data['data']['wbi_img']['sub_url'];
	    $img_key = substr(strrchr($img_url, '/'), 1, -4);
	    $sub_key = substr(strrchr($sub_url, '/'), 1, -4);
	    return ['img_key' => $img_key, 'sub_key' => $sub_key];
	}

	function get_bili_query($parameters)
	{
		
	    $img_key_sub_key = $this->getWbiKeys();
	    $params = [];
	    foreach ($parameters as $key => $value) {
	        $params[$key] = $value;
	    }
	    return $this->encWbi(
	        $params,
	        $img_key_sub_key['img_key'],
	        $img_key_sub_key['sub_key']
	    );
	}

	function get_Url($url) {
	    $ifpost = 0;
	    $datafields = '';
	    $cookiefile = '';
	    $user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36";

	    //$user_agent =Request::header('User-Agent');
	    $v = false;
	    //构造随机ip
	    $ip_long = array(
	        array('607649792', '608174079'), //36.56.0.0-36.63.255.255
	        array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
	        array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
	        array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
	        array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
	        array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
	        array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
	        array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
	        array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
	        array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
	    );
	    $rand_key = mt_rand(0, 9);
	    $ip= long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
	//模拟http请求header头
	    $header = array("Connection: Keep-Alive","Accept: text/html, application/xhtml+xml, */*", "Pragma: no-cache", "Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3","User-Agent: .$user_agent",'CLIENT-IP:'.$ip,'X-FORWARDED-FOR:'.$ip,'referer:https://space.bilibili.com/','Cookie:SESSDATA=02eca6d5%2C1759658193%2C4062e%2A41CjD7LUeo2T24vXtrx211w7wpEmuZlj7av1m3uuVHRKBl3zhQrzHFMdC461chG4v-0K0SVk1OeGVZYS1YX2o2TEEtU0lkVVhjNG1BdlVxWGRhUzN6aWlZODJxU08zNkdoNllvcXJUYk1PUFd1Ny0xcXNqRnFzUEJPMUZIM2o4MDMzblg5MG55Um53IIE');
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_HEADER, $v);
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	    $ifpost && curl_setopt($ch, CURLOPT_POST, $ifpost);
	    $ifpost && curl_setopt($ch, CURLOPT_POSTFIELDS, $datafields);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	    $cookiefile && curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
	    $cookiefile && curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
	    curl_setopt($ch,CURLOPT_TIMEOUT,60); //允许执行的最长秒数
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	    $ok = curl_exec($ch);
	    curl_close($ch);
	    unset($ch);
	    return $ok;
	}

	function getUrl($url) {
	    // 初始化cURL

	   $headers[] = "Content-type: application/x-www-form-urlencoded";

    	$curl = curl_init(); // 启动一个CURL会话

		curl_setopt($curl, CURLOPT_URL, $url);

		curl_setopt($curl, CURLOPT_HEADER, 0);

		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查

		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在

		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		 
		// 执行cURL会话
		$html = curl_exec($curl);
	    
	    return $html;
	}

	public function __invoke()
	{
		




		$videos = Video::query()->where('type','bilibli')->whereNull('video_url')->where("created_at",">=","2025-02-01")->get();
		//$videos = Video::query()->where('id',18)->get();

		foreach($videos as $video){

			$this->execute($video);
			echo $video->id;
			sleep(2);
		}
		
		

		//Dinglog::text("========== refresh seckill product num end ......");
	}


	 private function curl($url, $header = null, $data = null)
    {
        $con = curl_init((string)$url);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($con, CURLOPT_AUTOREFERER, 1);
        if (isset($header)) {
            curl_setopt($con, CURLOPT_HTTPHEADER, $header);
        }
        if (isset($data)) {
            curl_setopt($con, CURLOPT_POST, true);
            curl_setopt($con, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($con, CURLOPT_TIMEOUT, 5000);
        $result = curl_exec($con);
        return $result;
    }
}
